package com.example.sunmiv1.adapter;

import android.content.Context;
//import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;

import com.example.sunmiv1.R;
import com.example.sunmiv1.dialog.AddMemberLabelDialog;
import com.example.sunmiv1.dialog.DeleteDialog;
import com.example.sunmiv1.entity.member.MemberLabelManagerInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.views.TopPopWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MemberLabelManagerAdapter extends BaseAdapter {

    private List<MemberLabelManagerInfo.DataBean.ListBean> listBeans;
    private ViewHolder viewHolder;
    private OperaCallback operaCallback;
    private Context context;
    private FragmentManager fragmentManager;
    private TopPopWindow topPopWindow;
    private LoadingDialog loadingDialog;

    public MemberLabelManagerAdapter(Context context, FragmentManager fragmentManager, List<MemberLabelManagerInfo.DataBean.ListBean> listBeans) {
        this.context = context;
        this.fragmentManager = fragmentManager;
        this.listBeans = listBeans;
        loadingDialog = new LoadingDialog(context);
    }

    @Override
    public int getCount() {
        return listBeans.size();
    }

    @Override
    public Object getItem(int position) {
        return listBeans.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_member_label_manager, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        MemberLabelManagerInfo.DataBean.ListBean bean = listBeans.get(position);
        viewHolder.labelAdapterIndex.setText((position + 1) + "");
        viewHolder.labelAdapterName.setText(bean.getName());
        viewHolder.labelAdapterNum.setText(bean.getVip_num() + "");
        viewHolder.labelAdapterAddTime.setText(bean.getCreated_at());
        if(topPopWindow!=null){
            topPopWindow.dismiss();
        }
        final ImageView more = viewHolder.labelAdapterMore;
        final int index = position;
        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (topPopWindow == null) {
                    topPopWindow = new TopPopWindow(context, v12 -> {
                        switch (v12.getId()) {
                            case R.id.popWindow_edit:
                                AddMemberLabelDialog.newInstance(listBeans.get(position).getId())
                                        .startShow(fragmentManager, "")
                                        .callback(o -> {
                                            operaCallback.success(0, 0);
                                        }).setCancelable(false);
                                break;
                            case R.id.popWindow_delete:
                                DeleteDialog.newInstance("是否確認刪除所選標籤！")
                                        .startShow(fragmentManager, "")
                                        .callback(o -> {
                                            deleteLabel(listBeans.get(position).getId(), index);
                                        })
                                        .setCancelable(false);
                                break;
                            default:
                                break;
                        }
                    });
                    //監聽窗口的焦點事件，點擊窗口外面則取消顯示
                    topPopWindow.getContentView().setOnFocusChangeListener((v1, hasFocus) -> {
                        if (!hasFocus) {
                            topPopWindow.dismiss();
                        }
                    });
                }
                //設置默認獲取焦點
                topPopWindow.setFocusable(true);
                //以某個控件的x和y的偏移量位置開始顯示窗口
                topPopWindow.showAsDropDown(more, 0, 0);
                //如果窗口存在，則更新
                topPopWindow.update();
            }
        });
        return convertView;
    }

    public interface OperaCallback {
        void success(int type, int position);
    }

    public void setCallback(OperaCallback operaCallback) {
        this.operaCallback = operaCallback;
    }

    static class ViewHolder {
        @BindView(R.id.labelAdapter_index)
        TextView labelAdapterIndex;
        @BindView(R.id.labelAdapter_name)
        TextView labelAdapterName;
        @BindView(R.id.labelAdapter_num)
        TextView labelAdapterNum;
        @BindView(R.id.labelAdapter_addTime)
        TextView labelAdapterAddTime;
        @BindView(R.id.labelAdapter_more)
        ImageView labelAdapterMore;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 刪除會員標籤
     */
    private void deleteLabel(String id, int position) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("label_id", id);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.DEL_VIP_LABEL, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            listBeans.remove(position);
                            notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
